package linkTest_1 
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.Socket;
	import flash.utils.ByteArray;
	/**
	 * 
	 * @author cain in liontravel 2010
	 */
	public class Config
	{
		private var _model:Model;
		private var _socket:Socket;
		public function Config(_mo:Model) 
		{
			_model = _mo;
		}
		/**
		 * 連線
		 * @param	_server
		 * @param	_port
		 */
		public function link(_server:String,_port:String):void 
		{
			_model.addEventListener(Model.LINK_SERVER_CH, onLINK_SERVER_CH);
			_model.server = _server;
			_model.port = _port;
		}
		/**
		 * 送出資料
		 * @param	_str
		 */
		public function sentData(_str:String):void 
		{
			if (_model.isLink) //有連線狀態下 
			{
				var _bb:ByteArray = new ByteArray();
				_bb.writeUTFBytes(_str);
				_socket.writeShort(_bb.length+3);
				_socket.writeByte(1);
				_socket.writeUTFBytes(_str);
				_model.output = "送出: " + _str;
				_socket.flush();
			}
		}
		private function onLINK_SERVER_CH(e:Event):void 
		{
			_model.removeEventListener(Model.LINK_SERVER_CH, onLINK_SERVER_CH);
			_model.output = "連線中..";
			_socket = new Socket();
			_socket.addEventListener(Event.CLOSE, closeHandler);
			_socket.addEventListener(Event.CONNECT, connectHandler);
			_socket.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			_socket. addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
			_socket.addEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);
			_socket.connect(_model.server,int(_model.port));
		}
		
		private function socketDataHandler(e:ProgressEvent):void 
		{
			var str:int = _socket.readShort();
			var str2:int = _socket.readByte();
			var str3:String = _socket.readUTFBytes(_socket.bytesAvailable); 
			_model.output = "收到資料 : " + str+"(長度) "+str2+"(指令) "+str3;
		}
		
		private function securityErrorHandler(e:SecurityErrorEvent):void 
		{
			_model.output = "伺服器錯誤.."+e;
		}
		
		private function ioErrorHandler(e:IOErrorEvent):void 
		{
			_model.output = "伺服器錯誤.."+e;
		}
		
		private function closeHandler(e:Event):void 
		{
			_model.isLink = false;
			_model.output = "伺服器斷線!";
		}
		
		private function connectHandler(e:Event):void 
		{
			_model.isLink = true;
			_model.output = "伺服器連線成功!";
		}
	}

}